package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

/**
 * 1123. 最深叶节点的最近公共祖先
 * 865. 具有所有最深节点的最小子树
 *
 * @Author liw
 * @Date 2021/5/22 11:15
 * @Version 1.0
 */
public class LcaDeepestLeaves {

    private int d = 0;
    private TreeNode t;

    public TreeNode lcaDeepestLeaves(TreeNode root) {
        find(root, 0);
        return t;
    }

    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        find(root, 0);
        return t;
    }

    private int find(TreeNode root, int n) {
        if (root == null) {
            return 0;
        }
        int l = find(root.left, n + 1);
        int r = find(root.right, n + 1);
        if (l == r && l + n >= d) {
            d = l + n;
            t = root;
        }
        return Math.max(l, r) + 1;
    }

}
